package org.aaron.demos.myviews;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.DiscretePathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * 自定义View对象
 * 
 * @author aaron
 * 
 */
public class DrawView extends View {
	float preX;
	float preY;
	private Path path;
	private Paint paint;
	private int VIEW_WIDTH = getResources().getDisplayMetrics().widthPixels;
	private int VIEW_HEIGHT = getResources().getDisplayMetrics().heightPixels;
	// 定义缓冲对象
	Bitmap cacheBitmap = null;
	private Canvas cacheCanvas = null;

	public DrawView(Context context, AttributeSet set) {
		super(context, set);
		cacheBitmap = Bitmap.createBitmap(VIEW_WIDTH, VIEW_HEIGHT, Config.ARGB_8888);
		cacheCanvas = new Canvas();
		path = new Path();
		cacheCanvas.setBitmap(cacheBitmap);
		paint = new Paint(Paint.DITHER_FLAG);
		paint.setColor(Color.RED);
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeWidth(2);
		paint.setAntiAlias(true);
		paint.setDither(true);

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		float x=event.getX();
		float y=event.getY();
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			path.moveTo(x, y);
			preX=x;
			preY=y;
			break;
		case MotionEvent.ACTION_MOVE:
			path.quadTo(preX, preY, x, y);
			preX=x;
			preY=y;
			break;
		case MotionEvent.ACTION_UP:
			//设置Path特效
			//paint.setPathEffect(new DiscretePathEffect(3f,10f));
			//设置Path路径文本
			cacheCanvas.drawTextOnPath("Aaron_OuYang", path, -8, 20, paint);
			cacheCanvas.drawPath(path, paint);
			path.reset();
			break;
		default:
			break;
		}
		invalidate();
		return true;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		Paint paint=new Paint();
		canvas.drawBitmap(cacheBitmap, 0, 0, paint);
		canvas.drawPath(path, paint);

	}
}
